<template>
  <div class="allcontent">
    <div class="search">
      <el-form   @submit.native.prevent  size="default"  ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="name">
          <el-input v-model="queryParams.name"  @keyup.enter.native="handleQuery" placeholder="请输入岗位名称模糊搜索"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button round plain type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button round plain type="warning" @click="handleResetQuery(queryFormRef)">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-button round plain icon="Edit"  size="default"
                v-if="userStore.hasPermission('system:post:add')"
                type="success"
                @click="handleOpenDialog()"
    >
      新增
    </el-button>
    <el-button round plain icon="Edit"  size="default"
               v-if="userStore.hasPermission('system:post:update')"
               type="primary"
               :disabled="removeIds.length != 1"
               @click="handleOpenDialog()"
    >
      修改
    </el-button>
    <el-button round  plain icon="Delete"    size="default"
                v-if="userStore.hasPermission('system:post:remove')"
                type="danger"
                :disabled="removeIds.length === 0"
                @click="handleDelete()"
    >
      删除
    </el-button>
    <div class="el-table">
      <el-table
          style="font-size:16px"
          ref="dataTableRef"
          v-loading="loading"
          :data="tableData"
          highlight-current-row
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
            key="name"
            label="岗位名称"
            prop="name"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="code"
            label="岗位编号"
            prop="code"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="sort"
            label="排序"
            prop="sort"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="remark"
            label="备注"
            prop="remark"
            min-width="150"
            align="center"
        />
        <el-table-column  label="操作"    width="150" >
          <template #default="scope">
            <el-button round
                v-if="userStore.hasPermission('system:post:update')"
                type="primary"
                size="default"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button round
                v-if="userStore.hasPermission('system:post:remove')"
                type="danger"
                size="default"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="el-pager">
      <el-pagination layout="total,sizes,prev, pager, next,jumper" :total="total"
                     :page-sizes="[10,20,30,40,50]" :pager-count="11"
                     size="default"  background  class="mt-4" :current-page="currentPage"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>
    <!-- 岗位表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        @close="handleCloseDialog"
    >
      <el-form size="default" ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="岗位名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="岗位编码" prop="code">
          <el-input v-model="formData.code"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" type="number"></el-input>
        </el-form-item>
        <el-form-item label="岗位状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio value="1">正常</el-radio>
            <el-radio value="0">禁止</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button round  size="default" plain icon="Edit" type="primary" @click="handleSubmit()">确定</el-button>
          <el-button round   size="default" plain  icon="Close"  @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import {page,info,edit,save,remove} from "@/api/post";
  import {ElMessage, ElMessageBox, ElTree, ElTable, type ElForm, type FormInstance} from 'element-plus'
  import {ref,reactive,watch,onMounted} from 'vue'
  import {useUserStore} from '@/stores/user.ts'
  const userStore = useUserStore()
  const queryFormRef = ref<FormInstance>();
  const dataFormRef = ref();

  const currentPage = ref(1)
  const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    queryParams.value.limit= val;
    handleQuery();
  }
  const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    currentPage.value= val;
    queryParams.value.page= val;
    handleQuery();
  }

  const loading = ref(false);
  const removeIds = ref<number[]>([]);
  const total = ref(0);



  const queryParams = ref({
    page: 1,
    limit: 10,
    name:null
  });

  // 岗位表格数据
  const tableData = ref([]);

  // 弹窗
  const dialog = reactive({
    title: "",
    visible: false,
  });
  // 岗位表单数据
  const formData = ref({
    id:null,
    status:'1',
    sort:'0',
    name:'',
    code:''
  });

  // 岗位表单校验规则
  const rules = reactive({
     name: [{ required: true, message: "请输入名称", trigger: "blur" }],
     code: [{ required: true, message: "请输入编码", trigger: "blur" }],
     sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
  });

  /** 查询岗位 */
  const handleQuery =()=> {
        loading.value = true;
          page(queryParams.value)
        .then((res) => {
          tableData.value = res.data.list;
          total.value = res.data.total;
        })
        .finally(() => {
          loading.value = false;
        });
  }

  /** 重置岗位查询 */
  const handleResetQuery = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    handleQuery();
  }

  /** 行复选框选中记录选中ID集合 */
  const handleSelectionChange=(selection: any)=> {
    removeIds.value = selection.map((item: any) => item.id);
  }

  /** 打开岗位弹窗 */
  const handleOpenDialog=(id?: number)=> {
    dialog.visible = true;
    if (id) {
      dialog.title = "修改岗位";
      info(id).then((res) => {
        Object.assign(formData.value, res.data);
      });
    }else if(removeIds.value.length > 0){
      if(removeIds.value.length > 1){
        ElMessage({
          type: 'warning',
          message: '编辑只能选择一行',
        })
        return;
      }
      dialog.title = "修改岗位";
      info(removeIds.value[0]).then((res) => {
        Object.assign(formData.value, res.data);
      });
    } else {
      dialog.title = "新增岗位";
    }
  }

  /** 提交岗位表单 */
  const handleSubmit =()=> {
    dataFormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        const id = formData.value.id;
        if (id) {
              edit(formData.value)
              .then(() => {
                ElMessage.success("修改成功");
                handleCloseDialog();
                handleResetQuery(queryFormRef.value);
              })
              .finally(() => (loading.value = false));
        } else {
              save(formData.value)
              .then(() => {
                ElMessage.success("新增成功");
                handleCloseDialog();
                handleResetQuery(queryFormRef.value);
              })
              .finally(() => (loading.value = false));
        }
      }
    });
  }

  /** 关闭岗位弹窗 */
  const handleCloseDialog=()=> {
    dialog.visible = false;
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
    formData.value.id = undefined;
  }

  /** 删除岗位 */
  const handleDelete=(id?: number)=> {
    const ids = id ?  [id] : removeIds.value;
    if (!ids) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(
        () => {
          loading.value = true;
              remove(ids)
              .then(() => {
                ElMessage.success("删除成功");
                handleResetQuery(queryFormRef.value);
              })
              .finally(() => (loading.value = false));
        },
        () => {
          ElMessage.info("已取消删除");
        }
    );
  }

  onMounted(() => {
    handleQuery();
  });
</script>
<style scoped>
.dialog-footer{
  text-align: center;
}
.search{
  margin-bottom: 10px;
}
.el-pager{
  padding: 2%;
  justify-content: flex-start;
  align-items: flex-start;
  position: absolute;
  bottom:0;
  right:0;
  margin-bottom:25px;
  width: 100%;
  background-color: white;
  z-index: 1;
}
.allcontent{
  height: 80vh;
  position: relative;
}
.el-table{
  max-height:70%;
  overflow: auto;
  z-index: 0;
}
.el-table::-webkit-scrollbar{
  display: none;
}
</style>